package com.eascs.web.o2o.web.filter;


import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.workflow.common.entity.sys.UserLogEntity;
import com.eascs.workflow.common.service.sys.UserLogService;

public class AccessInterceptorAdapter extends HandlerInterceptorAdapter {
	Logger logger = LoggerFactory.getLogger(AccessInterceptorAdapter.class);

	@Reference
	private UserLogService userLogService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		// 记录访问日志
		try {
			String requestUri = request.getRequestURI();
			//过滤监控和首页记录
			if (!"/".equals(requestUri) && !"/system-admin/monitor/status".equals(requestUri)) {
				logger.debug("access log,url:{},ip:{}", request.getRequestURI(), request.getRemoteAddr());
				User user = UserHolder.getUser();
				UserLogEntity userLogEntity = new UserLogEntity();
				if (null != user) {
					userLogEntity.setLoginName(user.getAccount());
				}
				userLogEntity.setServerName(request.getHeader("host"));
				userLogEntity.setIp(request.getRemoteAddr());
				userLogEntity.setRefer(request.getHeader("referer"));
				userLogEntity.setParams(request.getQueryString());
				userLogEntity.setAgent(request.getHeader("user-agent"));
				userLogEntity.setUrl(requestUri);
				userLogEntity.setCreateTime(new Date());
				userLogService.writeLog(userLogEntity);
			}
		} catch (Exception e) {
			logger.error("记录用户访问日志失败,errMsg:{}", e);
			e.printStackTrace();
		}
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
}
